package com.wm.eduService.controller;


import com.alibaba.nacos.client.utils.StringUtils;
import com.wm.commonutils.R;
import com.wm.commonutils.result.ResultCode;
import com.wm.eduService.client.VodClient;
import com.wm.eduService.entity.EduVideo;
import com.wm.eduService.service.EduVideoService;
import com.wm.servicebase.exceptionhandle.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author sshdg
 * @since 2020-10-01
 */
@RestController
//@CrossOrigin
@Api(tags = "小节管理")
@RequestMapping("/eduService/video")
public class EduVideoController {

    @Autowired
    EduVideoService videoService;

    @Autowired
    VodClient vodClient;

    @ApiOperation("添加课程视频")
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo video){

        boolean saveResult = videoService.save(video);
        if (!saveResult){
            throw GuliException.from(ResultCode.SAVE_ERROR);
        }
        return  R.ok();
    }
    @ApiOperation("更新小节")
    @PutMapping("/updateVideo")
    public R updateVideo(@RequestBody EduVideo video){

        boolean updateResult = videoService.updateById(video);
        if (!updateResult){
            throw GuliException.from(ResultCode.UPDATE_ERROR);
        }
        return  R.ok();
    }

    @ApiOperation("根据id查询小节")
    @GetMapping("/getVideo/{id}")
    public R getVideoById(@PathVariable String id){
        EduVideo video = videoService.getById(id);
        return R.ok().data("video",video);
    }

    @ApiOperation("根据id删除小节、视频")
    @DeleteMapping("/{id}")
    /**
     * 删除小节，同时删除对应的阿里云视频
     */
    public R deleteVideo(@PathVariable  String id){

        EduVideo video = videoService.getById(id);
        String videoSourceId = video.getVideoSourceId();

        if(StringUtils.isNotBlank(videoSourceId)){
            //根据视频id  远程调用实现视频删除
            R r = vodClient.removeAliyunVideo(videoSourceId);
            if (r.getCode().equals(ResultCode.ERROR.getCode())){
                throw GuliException.from(ResultCode.DELETE_ERROR);
            }
        }

        //2.删除小节
        boolean b = videoService.removeById(id);
        if (!b){
            throw GuliException.from(ResultCode.DELETE_ERROR);
        }
        return R.ok();
    }



}

